package com.evaluation_system.service.impl;

import com.evaluation_system.service.RunPyService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class RunPyServiceImpl implements RunPyService {
    private static final String PYTHON_EXECUTABLE = "python3";
    @Override
    public byte[] RulesAnalysis(String pyFilePath,String geneaateTxtFilePath) {
        String pythonScriptPath = pyFilePath;
        String pythonExecutable = PYTHON_EXECUTABLE; // 或使用完整路径 "C:\\Python39\\python.exe"

        try {
            // 检查文件是否存在
            File scriptFile = new File(pythonScriptPath);
            if (!scriptFile.exists()) {
                throw new RuntimeException(" RulesAnalysis Python 脚本不存在: " + pythonScriptPath);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Python] " + line);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
            e.printStackTrace();
        }

        String relativePath =geneaateTxtFilePath;

        try {
            // 转换为绝对路径（基于当前工作目录）
            byte[] fileBytes = Files.readAllBytes(Paths.get(relativePath));
            System.out.println("文件大小: " + fileBytes.length + " 字节");

            // 打印内容（UTF-8编码）
            System.out.println(new String(fileBytes, "UTF-8"));

            return fileBytes;

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());

            // 调试：打印当前工作目录和完整路径
            System.out.println("当前工作目录: " + System.getProperty("user.dir"));
            System.out.println("尝试访问的路径: " + Paths.get(relativePath).toAbsolutePath());
        }
        return new byte[0];
    }

    @Override
    public byte[] ApplicationAnalysis(String s,String s1) {
        String pythonScriptPath = s;
        String pythonExecutable = PYTHON_EXECUTABLE; // 或使用完整路径 "C:\\Python39\\python.exe"

        try {
            // 检查文件是否存在
            File scriptFile = new File(pythonScriptPath);
            if (!scriptFile.exists()) {
                throw new RuntimeException("ApplicationAnalysis Python 脚本不存在: " + pythonScriptPath);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Python] " + line);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
            e.printStackTrace();
        }

        String relativePath = s1;

        try {
            // 转换为绝对路径（基于当前工作目录）
            byte[] fileBytes = Files.readAllBytes(Paths.get(relativePath));
            System.out.println("文件大小: " + fileBytes.length + " 字节");

            // 打印内容（UTF-8编码）
            System.out.println(new String(fileBytes, "UTF-8"));

            return fileBytes;

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());

            // 调试：打印当前工作目录和完整路径
            System.out.println("当前工作目录: " + System.getProperty("user.dir"));
            System.out.println("尝试访问的路径: " + Paths.get(relativePath).toAbsolutePath());
        }
        return new byte[0];
    }

    @Override
    public byte[] ReplyAttack(String pyFilePath, String generateTxtFilePath) {
        String pythonScriptPath = pyFilePath;
        String pythonExecutable = PYTHON_EXECUTABLE;

        try {
            // 检查文件是否存在
            File scriptFile = new File(pythonScriptPath);
            if (!scriptFile.exists()) {
                throw new RuntimeException("ReplyAttack Python 脚本不存在: " + pythonScriptPath);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Python] " + line);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
            e.printStackTrace();
        }

        String relativePath = generateTxtFilePath;

        try {
            // 转换为绝对路径（基于当前工作目录）
            byte[] fileBytes = Files.readAllBytes(Paths.get(relativePath));
            System.out.println("文件大小: " + fileBytes.length + " 字节");

            // 打印内容（UTF-8编码）
//            System.out.println(new String(fileBytes, "UTF-8"));

            return fileBytes;

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());

            // 调试：打印当前工作目录和完整路径
            System.out.println("当前工作目录: " + System.getProperty("user.dir"));
            System.out.println("尝试访问的路径: " + Paths.get(relativePath).toAbsolutePath());
        }
        return new byte[0];
    }

    @Override
    public byte[] XssAttack(String pyFilePath, String generateTxtFilePath) {
        String pythonScriptPath = pyFilePath;
        String pythonExecutable = PYTHON_EXECUTABLE;

        try {
            // 检查文件是否存在
            File scriptFile = new File(pythonScriptPath);
            if (!scriptFile.exists()) {
                throw new RuntimeException("Xss Python 脚本不存在: " + pythonScriptPath);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Python] " + line);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
            e.printStackTrace();
        }

        String relativePath = generateTxtFilePath;

        try {
            // 转换为绝对路径（基于当前工作目录）
            byte[] fileBytes = Files.readAllBytes(Paths.get(relativePath));
            System.out.println("文件大小: " + fileBytes.length + " 字节");

            // 打印内容（UTF-8编码）
//            System.out.println(new String(fileBytes, "UTF-8"));

            return fileBytes;

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());

            // 调试：打印当前工作目录和完整路径
            System.out.println("当前工作目录: " + System.getProperty("user.dir"));
            System.out.println("尝试访问的路径: " + Paths.get(relativePath).toAbsolutePath());
        }
        return new byte[0];
    }

    @Override
    public byte[] SqlAttack(String pyFilePath, String generateTxtFilePath) {
        String pythonScriptPath = pyFilePath;
        String pythonExecutable = PYTHON_EXECUTABLE;

        try {
            // 检查文件是否存在
            File scriptFile = new File(pythonScriptPath);
            if (!scriptFile.exists()) {
                throw new RuntimeException("sql Python 脚本不存在: " + pythonScriptPath);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Python] " + line);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
            e.printStackTrace();
        }

        String relativePath = generateTxtFilePath;

        try {
            // 转换为绝对路径（基于当前工作目录）
            byte[] fileBytes = Files.readAllBytes(Paths.get(relativePath));
            System.out.println("文件大小: " + fileBytes.length + " 字节");

            // 打印内容（UTF-8编码）
//            System.out.println(new String(fileBytes, "UTF-8"));

            return fileBytes;

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());

            // 调试：打印当前工作目录和完整路径
            System.out.println("当前工作目录: " + System.getProperty("user.dir"));
            System.out.println("尝试访问的路径: " + Paths.get(relativePath).toAbsolutePath());
        }

        return new byte[0];
    }


}
